package com.thiswhyme.seata.account.service;

import com.thiswhyme.common.expection.BusinessException;
import com.thiswhyme.seata.account.domain.Account;
import com.thiswhyme.seata.account.repository.AccountMapper;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: thiswhyme
 * @date: 2020/9/4
 */
@Service
@Slf4j
public class AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Transactional(rollbackFor = Exception.class)
    public boolean reduceBalance(Long userId, Integer price) {
        log.info("当前 XID: {}", RootContext.getXID());
        checkBalance(userId, price);

        log.info("开始扣减用户 {} 余额", userId);
        Integer record = accountMapper.reduceBalance(userId, price);
        log.info("扣减用户 {} 余额结果:{}", userId, record > 0 ? "操作成功" : "扣减余额失败");
        return record > 0;
    }

    private void checkBalance(Long userId, Integer price) {
        log.info("检查用户 {} 余额", userId);
        Account account = accountMapper.selectById(userId);
        if (null == account) {
            log.warn("用户{}的账户不存在", account);
            throw new BusinessException("账户不存在");
        }
        if (null != account && account.getBalance() < price) {
            log.warn("用户 {} 余额不足，当前余额:{}", userId, account.getBalance());
            throw new BusinessException("余额不足");
        }
    }
}
